/**
 * Copyright (C) 2012 The SkyTvOS Project
 * <p/>
 * Version     Date           Author
 * ─────────────────────────────────────
 * 2014-6-17         luwei
 */

package com.tianci.appstore.ui.widget;

import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;

import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnFocusChangeListener;
import android.view.View.OnKeyListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;

import com.coocaa.x.app.framework.app.LiteAppApplication;
import com.coocaa.x.framework.utils.LogUtils;
import com.tianci.appstore.AppListActivity;
import com.tianci.appstore.AppListActivity.ListActivityType;
import com.tianci.appstore.R;
import com.tianci.appstore.SearchActivity;
import com.tianci.appstore.controller.AppStoreBaseController;
import com.tianci.appstore.controller.AppStoreBaseController.UpdateDownloadCountHandler;
import com.tianci.appstore.controller.AppStoreMainPageController;
import com.tianci.appstore.ui.SkinManager;
import com.tianci.appstore.ui.data.SkyListAppData.ListType;
import com.tianci.appstore.utils.SkyConstants;

public class LeftImageButtonLayer extends LinearLayout implements OnClickListener, OnFocusChangeListener, OnKeyListener,
        UpdateDownloadCountHandler {
    private int mSize = 0;
    private Context mContext = null;
    private HashSet<Button> mButtons = new HashSet<Button>();
    private int mDefalutSize = SkyConstants.Dpi(32);
    private int mDefalutColor = Color.WHITE;
    private OnLayerFocusChangeListener mLayerFocusChangeListener = null;
    private int mKeyCode = 0;
    private boolean isInMainPage = false;

    public LeftImageButtonLayer(Context context) {
        super(context);
        setOrientation(LinearLayout.HORIZONTAL);
        setGravity(Gravity.RIGHT | Gravity.CENTER_VERTICAL);
        AppStoreBaseController.addUpdateDownloadCountHandler(this);
        this.mContext = context;
    }

    public interface OnLayerFocusChangeListener {
        public void onFocusChange(View leaveView, int leaveIndex, int leaveKey);
    }

    public void setLayerFocusChangeListener(OnLayerFocusChangeListener listener) {
        this.mLayerFocusChangeListener = listener;
    }

    public void initDefaultParams() {
        initLayerParams(2, new int[]{R.drawable.icon_search, R.drawable.icon_download},
                new String[]{getResources().getString(R.string.search), ""});
    }

    public void setInMainPage(boolean mainpage){
        this.isInMainPage = mainpage;
    }

    public void initLayerParams(int size, int[] images, String[] name) {
        this.mSize = size;
        if (size > 0 && size == images.length && size == name.length) {
            for (int i = 0; i < size; i++) {
                Button button = new Button(mContext);
                LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
                        LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
                button.setGravity(Gravity.CENTER);
                button.setLayoutParams(params);
                button.setMinWidth(SkyConstants.Div(132));
                SkinManager.setBackground(button, R.drawable.search_selector);
//                if (i == 0)
//                {
//                    button.setPadding(SkyConstants.Div(40), SkyConstants.Div(27), SkyConstants.Div(40), SkyConstants.Div(27));
//                }else
//                {
//                    button.setPadding(SkyConstants.Div(40), SkyConstants.Div(27), SkyConstants.Div(40), SkyConstants.Div(27));
//                }
                if (i == size - 1) {
                    button.setId(99);
                    button.setNextFocusRightId(button.getId());
                    button.setOnKeyListener(new OnKeyListener() {

                        @Override
                        public boolean onKey(View v, int keyCode, KeyEvent event) {
                            if (keyCode == KeyEvent.KEYCODE_DPAD_RIGHT) {
                                return true;
                            }
                            return false;
                        }
                    });
                }
                Drawable myImage = SkinManager.getResDrawable(images[i]);
                myImage.setBounds(1, 1, SkyConstants.Div(43), SkyConstants.Div(42));
                button.setCompoundDrawables(myImage, null, null, null);
                button.setCompoundDrawablePadding(SkyConstants.Div(5));
                button.setText(name[i]);
                button.setOnKeyListener(this);
                button.setOnClickListener(this);
                button.setTextColor(mDefalutColor);
                button.setTextSize(mDefalutSize);
                button.setOnFocusChangeListener(this);
                button.setTag(i);
                addView(button);
                if (i < size - 1) {
                    ImageView view = new ImageView(mContext);
                    LinearLayout.LayoutParams imgParams = new LinearLayout.LayoutParams(
                            2, SkyConstants.Div(40));
                    view.setBackgroundColor(Color.parseColor("#344d6a"));
                    addView(view, imgParams);
                }
            }
        } else {
            throw new RuntimeException("please check the button layer params");
        }
    }

    public void updateImageView(int index, int id) {
        if (index < getChildCount()) {
            ((Button) getChildAt(index)).setCompoundDrawables(SkinManager.getResDrawable(id), null, null, null);
        }
    }

    public void updatePointText(int index, String string) {
        if (index < getChildCount()) {
            ((Button) getChildAt(index)).setText(string);
        }
    }


    @Override
    public void onClick(View v) {
        if (!LiteAppApplication.checkNetworkConnection(TipToast.showNetIsNotConnectedToastRunnable))
            return;
        switch ((Integer) v.getTag()) {
            case 0:
                Intent intent = new Intent();
                intent.setClass(mContext, SearchActivity.class);
                mContext.startActivity(intent);
                if (isInMainPage){
                    Map<String,String> params = new HashMap<String, String>();
                    params.put("entry_name", "搜索");
                    LogUtils.submit(LogUtils.PRODUCTID_APPSTORE, "as2_main_entry_onclick", params);
                }
                break;
            case 1:
                AppListActivity.type = ListActivityType.DOWNLOAD_LIST;
                Intent intent1 = new Intent();
                intent1.setClass(mContext, AppListActivity.class);
                intent1.putExtra("listType", ListType.DOWNLOAD_LIST.toString());
                mContext.startActivity(intent1);
                break;
            default:
                break;
        }

    }

    private boolean isLayerFocusd() {
        int count = getChildCount();
        for (int i = 0; i < count; i++) {
            if (getChildAt(i).isFocused()) {
                return true;
            }
        }
        return false;
    }

    @Override
    public void onFocusChange(View v, boolean hasFocus) {
        if (!hasFocus) {
            if (!isLayerFocusd()) {
                if (mLayerFocusChangeListener != null) {
                    mLayerFocusChangeListener.onFocusChange(v, (Integer) v.getTag(), mKeyCode);
                }
            }
        }
    }

    @Override
    public boolean onKey(View v, int keyCode, KeyEvent event) {
        if (event.getAction() == KeyEvent.ACTION_DOWN) {
            mKeyCode = keyCode;
        }
        return false;
    }

    @Override
    public void updateDownloadCount(int count) {
        updatePointText(2, String.valueOf(count));
    }

    public void onDestory() {
        AppStoreBaseController.removeUpdateDownloadCountHandler(this);
    }

    public boolean isChildFocused() {
        int size = getChildCount();
        for (int i = 0; i < size; i++) {
            if (getChildAt(i).isFocused()) {
                return true;
            }
        }
        return false;
    }

    public void audioMatch(String command) {
        if (command.equals("下载管理")) {
            onClick(getChildAt(2));
        } else if (command.equals("搜索")) {
            onClick(getChildAt(0));
        }
    }
}
